from flask import Flask, request, jsonify
from flask_cors import CORS
import pyodbc

app = Flask(__name__)
CORS(app)

# SQL Server连接字符串
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=exam;UID=sa;PWD=123456')
cursor = conn.cursor()

# 登录API
@app.route('/api/login', methods=['POST'])
def login():
    data = request.get_json()

    username = data["username"]
    password = data["password"]

    sql = "select * from sys_user where username=? and password=?"
    cursor.execute(sql, (username, password))
    result = cursor.fetchone()

    if result:
        return jsonify({'code': 200, 'msg': '登录成功'})
    else:
        return jsonify({'code': 404, 'msg': '用户名或密码错误'})

# 注册API
@app.route('/api/register', methods=['POST'])
def register():
    data = request.get_json()

    username = data["username"]
    password = data["password"]

    sql = "insert into sys_user(username, password) values(?, ?)"
    cursor.execute(sql, (username, password))
    conn.commit()
    return jsonify({'code': 200, 'msg': '注册成功'})

# 获取所有用户API
@app.route('/api/sys_user', methods=['GET'])
def get_users():
    sql = "select * from sys_user"
    cursor.execute(sql)
    results = cursor.fetchall()
    users = []
    for row in results:
        user = {
            'id': row.id,
            'username': row.username,
            'password': row.password
        }
        users.append(user)
    return jsonify(users)

if __name__ == '__main__':
    app.run(debug=True)